-- ============================================
-- ROCKET CASINO - MACHINE A SOUS
-- Architecture :
--   - Le COMPUTER (son propre terminal) = le jeu (login clavier,
--     mise, rouleaux, gains) : c'est ici que le joueur interagit.
--   - Le MONITOR mural = pure decoration (banniere "ROCKET CASINO"
--     + Poke Ball qui tourne), jamais touche, jamais utilise pour jouer.
-- Les deux tournent en meme temps sur le meme ordinateur.
--
-- Fichier requis dans le meme dossier : client_solde.lua
-- (login.lua n'est plus utilise ici : la connexion se fait au clavier
--  physique directement dans le terminal du computer)
-- ============================================

local bank = dofile("client_solde.lua")
math.randomseed(os.epoch and os.epoch("utc") or os.time())

-- ============================================
-- PARTIE 1 : BANNIERE DECORATIVE SUR LE MONITOR
-- ============================================

local function buildBannerLoop()
    local mon = peripheral.find("monitor")
    if not mon then
        return nil -- pas de moniteur branche, on se passe de la deco
    end

    mon.setTextScale(0.5)
    mon.setBackgroundColor(colors.black)
    mon.clear()
    local W, H = mon.getSize()

    local FRAME_DELAY = 0.1
    local ROTATION_SPEED = 0.22
    local SUBTITLE_TEXT = "   *** PREPARE FOR TROUBLE * MAKE IT DOUBLE ***   BIENVENUE AU ROCKET CASINO   *** LES JACKPOTS SONT (PRESQUE) GARANTIS ***   "

    local function newCanvas(bg)
        local c = {}
        for y = 1, H do
            c[y] = {}
            for x = 1, W do
                c[y][x] = { bg = bg, ch = " ", fg = colors.white }
            end
        end
        return c
    end

    local function px(canvas, x, y, bg, ch, fg)
        x, y = math.floor(x + 0.5), math.floor(y + 0.5)
        if x >= 1 and x <= W and y >= 1 and y <= H then
            local cell = canvas[y][x]
            if bg then cell.bg = bg end
            if ch then
                cell.ch = ch
                cell.fg = fg or cell.fg
            end
        end
    end

    local function render(canvas)
        local toBlit = colors.toBlit
        for y = 1, H do
            local row = canvas[y]
            local chars, fgs, bgs = {}, {}, {}
            for x = 1, W do
                local cell = row[x]
                chars[x] = cell.ch
                fgs[x] = toBlit(cell.fg)
                bgs[x] = toBlit(cell.bg)
            end
            mon.setCursorPos(1, y)
            mon.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
        end
    end

    local function fillEllipse(canvas, cx, cy, rx, ry, color)
        if rx <= 0 or ry <= 0 then return end
        for y = math.floor(cy - ry), math.ceil(cy + ry) do
            local dy = (y - cy) / ry
            local t = 1 - dy * dy
            if t >= 0 then
                local dx = rx * math.sqrt(t)
                for x = math.floor(cx - dx), math.ceil(cx + dx) do
                    px(canvas, x, y, color)
                end
            end
        end
    end

    local FONT = {
        R = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" },
        O = { ".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###." },
        C = { ".####", "#....", "#....", "#....", "#....", "#....", ".####" },
        K = { "#...#", "#..#.", "#.#..", "##...", "#.#..", "#..#.", "#...#" },
        E = { "#####", "#....", "#....", "####.", "#....", "#....", "#####" },
        T = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "..#.." },
        A = { ".###.", "#...#", "#...#", "#####", "#...#", "#...#", "#...#" },
        S = { ".####", "#....", "#....", ".###.", "....#", "....#", "####." },
        I = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "#####" },
        N = { "#...#", "##..#", "#.#.#", "#..##", "#...#", "#...#", "#...#" },
    }

    local function drawGlyph(canvas, pattern, x0, y0, scale, color)
        for row = 1, #pattern do
            local line = pattern[row]
            for col = 1, #line do
                if line:sub(col, col) == "#" then
                    for sy = 0, scale - 1 do
                        for sx = 0, scale - 1 do
                            px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
                        end
                    end
                end
            end
        end
    end

    local function drawText(canvas, x, y, text, fg, bg)
        for i = 1, #text do
            px(canvas, x + i - 1, y, bg, text:sub(i, i), fg)
        end
    end

    local CHASE_COLORS = { colors.yellow, colors.orange, colors.red, colors.orange }
    local function drawMarquee(canvas, tick)
        local n = #CHASE_COLORS
        for x = 1, W do
            local c = CHASE_COLORS[((x + tick) % n) + 1]
            px(canvas, x, 1, c)
            px(canvas, x, H, c)
        end
        for y = 1, H do
            local c = CHASE_COLORS[((y + tick) % n) + 1]
            px(canvas, 1, y, c)
            px(canvas, W, y, c)
        end
    end

    local ACCENT_COLORS = { colors.yellow, colors.orange, colors.white, colors.orange }
    local function drawBigTitle(canvas, tick, word1, word2, redIdx1, redIdx2)
        local LETTER_W, GAP_W, WORD_GAP = 5, 1, 4

        local function wordUnits(word)
            return #word * LETTER_W + (#word - 1) * GAP_W
        end
        local totalUnits = wordUnits(word1) + WORD_GAP + wordUnits(word2)

        local scale = math.max(1, math.floor((W - 6) / totalUnits))
        local totalWidth = totalUnits * scale
        local startX = math.max(2, math.floor((W - totalWidth) / 2) + 1)
        local startY = 3

        local accent = ACCENT_COLORS[(math.floor(tick / 3) % #ACCENT_COLORS) + 1]

        local function drawWord(word, x, redLetterIndex)
            for i = 1, #word do
                local letter = word:sub(i, i)
                local pattern = FONT[letter]
                local color = (redLetterIndex and i == redLetterIndex) and colors.red or accent
                if pattern then
                    drawGlyph(canvas, pattern, x + 1, startY + 1, scale, colors.black)
                    drawGlyph(canvas, pattern, x, startY, scale, color)
                end
                x = x + (LETTER_W + GAP_W) * scale
            end
            return x
        end

        local cursor = startX
        cursor = drawWord(word1, cursor, redIdx1)
        cursor = cursor + (WORD_GAP - GAP_W) * scale
        drawWord(word2, cursor, redIdx2)

        return startY + 7 * scale + 2
    end

    local function drawSubtitle(canvas, tick)
        local y = H - 2
        local len = #SUBTITLE_TEXT
        local offset = tick % len
        local scrolled = SUBTITLE_TEXT:sub(offset + 1) .. SUBTITLE_TEXT:sub(1, offset)
        local visible = scrolled:sub(1, math.max(0, W - 4))
        drawText(canvas, 3, y, visible, colors.yellow, colors.black)
    end

    local function drawPokeball(canvas, cx, cy, r, angle)
        local squish = math.max(0.12, math.abs(math.cos(angle)))
        local rx = r * squish
        local ry = r

        fillEllipse(canvas, cx, cy, rx + 1.2, ry + 1.2, colors.gray)

        for y = math.floor(cy - ry), math.ceil(cy + ry) do
            local dy = (y - cy) / ry
            local t = 1 - dy * dy
            if t >= 0 then
                local dx = rx * math.sqrt(t)
                local color
                if y < cy - ry * 0.08 then
                    color = colors.black
                elseif y > cy + ry * 0.08 then
                    color = colors.red
                else
                    color = colors.lightGray
                end
                for x = math.floor(cx - dx), math.ceil(cx + dx) do
                    px(canvas, x, y, color)
                end
            end
        end

        for x = math.floor(cx - rx), math.ceil(cx + rx) do
            px(canvas, x, cy, colors.black)
        end

        local buttonR = math.max(1, r * 0.28 * squish)
        fillEllipse(canvas, cx, cy, buttonR + 0.6, buttonR + 0.6, colors.black)
        fillEllipse(canvas, cx, cy, buttonR, buttonR, colors.white)
        fillEllipse(canvas, cx, cy, buttonR * 0.5, buttonR * 0.5, colors.lightGray)

        if squish > 0.55 then
            local scale = math.max(1, math.floor(r * squish / 5))
            local rx0 = math.floor(cx - 2 * scale)
            local ry0 = math.floor(cy - ry * 0.75)
            for dx = -1, 1 do
                for dy = -1, 1 do
                    if dx ~= 0 or dy ~= 0 then
                        drawGlyph(canvas, FONT.R, rx0 + dx, ry0 + dy, scale, colors.black)
                    end
                end
            end
            drawGlyph(canvas, FONT.R, rx0, ry0, scale, colors.red)
        end
    end

    local function drawIdleFrame(tick, angle)
        local canvas = newCanvas(colors.black)
        drawMarquee(canvas, tick)
        local contentTop = drawBigTitle(canvas, tick, "ROCKET", "CASINO", 1, 1)

        local centerX = math.floor(W / 2)
        local availableH = math.max(6, (H - 3) - contentTop)
        local centerY = contentTop + math.floor(availableH / 2)
        local shapeR = math.floor(math.min(W * 0.22, availableH * 0.45))
        drawPokeball(canvas, centerX, centerY, shapeR, angle)

        drawSubtitle(canvas, tick)
        render(canvas)
    end

    return function()
        local tick, angle = 0, 0
        while true do
            drawIdleFrame(tick, angle)
            angle = angle + ROTATION_SPEED
            tick = tick + 1
            sleep(FRAME_DELAY)
        end
    end
end

-- ============================================
-- PARTIE 2 : LE JEU, SUR LE TERMINAL DU COMPUTER
-- ============================================

-- Symboles maison, thematique Team Rocket (rouge / noir / or)
local SYMBOLS = {
    { symbol = "@", color = colors.red,    value = 20, name = "Poke Ball Rocket" },
    { symbol = "7", color = colors.yellow, value = 10, name = "Sept doré" },
    { symbol = "*", color = colors.orange, value = 7,  name = "Etoile" },
    { symbol = "^", color = colors.red,    value = 5,  name = "Flamme" },
    { symbol = "$", color = colors.yellow, value = 3,  name = "Piece d'or" },
}

local MISE_MIN, MISE_MAX, MISE_STEP, MISE_DEFAULT = 1, 20, 1, 1
local bet = MISE_DEFAULT

local function centerText(y, text, textColor, bgColor)
    local w = select(1, term.getSize())
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.max(1, math.floor((w - #text) / 2) + 1)
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", x2 - x1 + 1))
    end
end

-- === GEOMETRIE DES ROULEAUX (calculee a chaque partie selon la taille du terminal) ===
local REEL_COUNT = 3
local SYM_W, SYM_H = 7, 3
local SEP_H = 1
local REEL_GAP = 2

local function randomSymbol()
    return math.random(1, #SYMBOLS)
end

local function drawSymbolBox(x1, y1, idx, isPayline)
    local sym = SYMBOLS[idx]
    local x2 = x1 + SYM_W - 1
    local y2 = y1 + SYM_H - 1
    term.setBackgroundColor(colors.black)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", SYM_W))
    end
    term.setTextColor(sym.color)
    local midY = y1 + math.floor(SYM_H / 2)
    local midX = x1 + math.floor((SYM_W - 1) / 2)
    term.setCursorPos(midX, midY)
    term.write(sym.symbol)

    if isPayline then
        term.setTextColor(colors.red)
        term.setCursorPos(x1, midY)
        term.write(">")
        term.setCursorPos(x2, midY)
        term.write("<")
    end
end

local function drawSeparator(x1, y, isPayline)
    term.setBackgroundColor(colors.black)
    term.setTextColor(isPayline and colors.red or colors.gray)
    term.setCursorPos(x1, y)
    term.write(string.rep("-", SYM_W))
end

local function makeGeometry()
    local w, h = term.getSize()
    local totalReelWidth = REEL_COUNT * SYM_W + (REEL_COUNT - 1) * REEL_GAP
    local reelsLeft = math.max(1, math.floor((w - totalReelWidth) / 2) + 1)
    local reelsTop = 8

    local geo = { w = w, h = h, left = reelsLeft, top = reelsTop }
    geo.rowTopY = reelsTop
    geo.sep1Y = geo.rowTopY + SYM_H
    geo.rowMidY = geo.sep1Y + SEP_H
    geo.sep2Y = geo.rowMidY + SYM_H
    geo.rowBotY = geo.sep2Y + SEP_H
    geo.reelBottom = geo.rowBotY + SYM_H - 1

    function geo.reelX(i)
        return reelsLeft + (i - 1) * (SYM_W + REEL_GAP)
    end

    return geo
end

local function drawReel(geo, i, reel)
    local x = geo.reelX(i)
    drawSymbolBox(x, geo.rowTopY, reel.top, false)
    drawSeparator(x, geo.sep1Y, true)
    drawSymbolBox(x, geo.rowMidY, reel.mid, true)
    drawSeparator(x, geo.sep2Y, true)
    drawSymbolBox(x, geo.rowBotY, reel.bot, false)
end

local function drawAllReels(geo, reels)
    for i, reel in ipairs(reels) do
        drawReel(geo, i, reel)
    end
end

local function drawHeader(player, points)
    fillArea(1, 1, select(1, term.getSize()), 3, colors.black)
    centerText(1, "== ROCKET CASINO - MACHINE A SOUS ==", colors.red)
    centerText(2, "Agent : " .. player, colors.yellow)
    centerText(3, "Points : " .. points .. "    Mise : " .. bet, colors.orange)
end

local function drawMessage(geo, text, textColor)
    fillArea(1, 6, geo.w, 6, colors.black)
    if text then
        centerText(6, text, textColor or colors.lightGray)
    end
end

local function drawFooter(geo, text, textColor)
    fillArea(1, geo.reelBottom + 1, geo.w, geo.h, colors.black)
    if text then
        centerText(geo.reelBottom + 2, text, textColor or colors.lightGray)
    end
end

local function drawMenu(geo)
    local w = geo.w
    local line = "[+] mise  [-] mise  [ENTREE] tourner  [q] quitter"
    fillArea(1, 5, w, 5, colors.black)
    centerText(5, line, colors.orange)
end

local function dollarRain(geo, ticks)
    local drops = {}
    for i = 1, 12 do
        drops[i] = { x = math.random(1, geo.w), y = math.random(-10, 0) }
    end

    for t = 1, ticks do
        for _, d in ipairs(drops) do
            term.setBackgroundColor(colors.black)
            term.setCursorPos(d.x, d.y)
            term.write(" ")
            d.y = d.y + 1
            if d.y > geo.h then
                d.x = math.random(1, geo.w)
                d.y = math.random(-6, 0)
            elseif d.y >= 1 then
                term.setTextColor(colors.yellow)
                term.setCursorPos(d.x, d.y)
                term.write("$")
            end
        end
        sleep(0.06)
    end

    for _, d in ipairs(drops) do
        term.setBackgroundColor(colors.black)
        term.setCursorPos(d.x, math.min(d.y, geo.h))
        term.write(" ")
    end
end

local function evaluateWin(i1, i2, i3, currentBet)
    if i1 == i2 and i2 == i3 then
        return SYMBOLS[i1].value * currentBet, "JACKPOT ! 3x " .. SYMBOLS[i1].name
    elseif i1 == i2 or i2 == i3 or i1 == i3 then
        local matchIdx = (i1 == i2) and i1 or ((i2 == i3) and i2 or i1)
        return math.floor(SYMBOLS[matchIdx].value / 2) * currentBet, "Petit gain ! 2x " .. SYMBOLS[matchIdx].name
    else
        return 0, nil
    end
end

local function playRound(player, points)
    local geo = makeGeometry()

    if points < bet then
        drawMessage(geo, "PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return points
    end

    local newBal1, err1 = bank.addBalance(player, -bet)
    if not newBal1 then
        drawMessage(geo, err1 or "Erreur banque, reessaie.", colors.red)
        sleep(2)
        return points
    end
    points = newBal1

    local reels = {}
    for i = 1, REEL_COUNT do
        reels[i] = { top = randomSymbol(), mid = randomSymbol(), bot = randomSymbol() }
    end

    local stopTicks = { 14, 20, 26 }
    local maxTick = stopTicks[REEL_COUNT]

    drawHeader(player, points)
    drawFooter(geo, "Les rouleaux tournent...", colors.white)

    for tick = 1, maxTick do
        for i, reel in ipairs(reels) do
            if tick <= stopTicks[i] then
                reel.top = reel.mid
                reel.mid = reel.bot
                reel.bot = randomSymbol()
            end
        end
        drawAllReels(geo, reels)
        sleep(0.04 + tick * 0.004)
    end

    local i1, i2, i3 = reels[1].mid, reels[2].mid, reels[3].mid
    local gain, message = evaluateWin(i1, i2, i3, bet)

    if gain > 0 then
        local newBal2 = bank.addBalance(player, gain)
        points = newBal2 or points
    end

    drawHeader(player, points)

    if gain > 0 then
        drawFooter(geo, message .. " (+" .. gain .. ")", colors.yellow)
        dollarRain(geo, 20)
        drawAllReels(geo, reels)
        drawHeader(player, points)
        drawFooter(geo, message .. " (+" .. gain .. ")", colors.yellow)
    else
        drawFooter(geo, "Perdu... reessaie !", colors.red)
    end

    sleep(1.5)
    return points
end

-- Connexion au clavier physique (pas de clavier virtuel : c'est le
-- terminal du computer, le joueur tape normalement)
local function authenticateKeyboard()
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(2, "=== ROCKET CASINO ===", colors.red)
    term.setCursorPos(1, 4)
    term.setTextColor(colors.white)
    term.write("Pseudo Minecraft : ")
    local username = read()

    while true do
        term.setTextColor(colors.white)
        term.write("Mot de passe : ")
        local password = read("*")
        local ok, err = bank.authenticate(username, password)
        if ok then
            return username
        else
            term.setTextColor(colors.red)
            print(err or "Erreur de connexion, reessaie.")
        end
    end
end

local function runSession()
    local player = authenticateKeyboard()
    local points = bank.getBalance(player)
    bet = MISE_DEFAULT

    local idleReels = {
        { top = 1, mid = 1, bot = 1 },
        { top = 2, mid = 2, bot = 2 },
        { top = 3, mid = 3, bot = 3 },
    }

    local playing = true
    while playing do
        local geo = makeGeometry()
        drawHeader(player, points)
        drawMenu(geo)
        drawMessage(geo, nil)
        drawAllReels(geo, idleReels)
        drawFooter(geo, "Mise min " .. MISE_MIN .. " - max " .. MISE_MAX, colors.gray)

        term.setCursorPos(1, geo.h)
        term.setBackgroundColor(colors.black)
        term.setTextColor(colors.white)
        term.write("> ")
        local cmd = read()

        if cmd == "+" then
            bet = math.min(MISE_MAX, bet + MISE_STEP)
        elseif cmd == "-" then
            bet = math.max(MISE_MIN, bet - MISE_STEP)
        elseif cmd == "q" or cmd == "Q" then
            playing = false
        else
            -- ENTREE (chaine vide) ou n'importe quoi d'autre = on tourne
            points = playRound(player, points)
        end
    end
end

local function gameLoop()
    while true do
        runSession()
    end
end

-- ============================================
-- LANCEMENT : moniteur (deco) + computer (jeu) en meme temps
-- ============================================

local bannerLoop = buildBannerLoop()

if bannerLoop then
    parallel.waitForAll(bannerLoop, gameLoop)
else
    gameLoop()
end